package com.fastcms.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fastcms.common.model.GptMessage;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChatGPTClient {

	public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
	
	public final static String ROLE_USER = "user";
	public final static String MODEL_35 = "gpt-3.5-turbo";
//	public final static String HEADER_AUTHORIZATION = "Bearer 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";
//	public final static String HEADER_AUTHORIZATION = "Bearer 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";
//	public final static String HEADER_AUTHORIZATION = "Bearer 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";//keedu 01
//	public final static String HEADER_AUTHORIZATION = "Bearer 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";//keedu 01
//	public final static String HEADER_AUTHORIZATION = "Bearer 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";//keedu 01
	public final static String HEADER_AUTHORIZATION = "Bearer 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";//keedu 01

	OkHttpClient client = null;

	private String role;
	private String model;
	private String content;
	private Integer readTimeout;


	Logger logger = LoggerFactory.getLogger(this.getClass());
	

	
	public ChatGPTClient(String role, String model, String content,Integer readTimeout) {
		super();
		this.role = role;
		this.model = model;
		this.content = content;
		this.readTimeout = readTimeout;
		
		client=new OkHttpClient.Builder()
		  .connectTimeout(60 , TimeUnit.SECONDS)
        .writeTimeout(60 ,TimeUnit.SECONDS)
        .readTimeout(readTimeout==null?60:readTimeout ,TimeUnit.SECONDS)
        .build();
	}
	
	public static ChatGPTClient.Builder Builder() {
        return new ChatGPTClient.Builder();
    }

	public static class Builder {
		private String role;
		private String model;
		private String content;
		private Integer readTimeout;
		
		Builder() {
		}
		
		public Builder role(String role) {
			this.role = role;
			return this;
		}

		public Builder model(String model) {
			this.model = model;
			return this;
		}

		public Builder content(String content) {
			this.content = content;
			return this;
		}
		
		public Builder readTimeout(Integer readTimeout) {
			this.readTimeout = readTimeout;
			return this;
		}

		public ChatGPTClient build() {
			return new ChatGPTClient(this.role,this.model, this.content,this.readTimeout);
		}
	}

//	{
//	    "model": "gpt-3.5-turbo",
//	    "messages": [{"role": "user", "content": "gen midjourney prompt:desigin a logo like IBM"}]
//	}

	public String chat() throws Exception {
		GptMessage message = new GptMessage();
		message.setRole(role);
		message.setContent(this.content);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("model", model);
		param.put("messages", new GptMessage[] { message });
		String url = "https://api.openai.com/v1/chat/completions";
		String body = JSONObject.toJSONString(param);
		logger.info("request  url: {}", url);
		logger.info("request body: {}", body);
		String resp = post(url, body);
		logger.info("response json: {}", resp);
		return resp;
	}

	private String post(String url, String json) throws IOException {
		RequestBody body = RequestBody.create(json, JSON);
		Request request = new Request.Builder()
				.url(url)
				.post(body)
				.header("Authorization", HEADER_AUTHORIZATION)
				.build();
		Response response = client.newCall(request).execute();
		return response.body().string();
	}

}
